const http = require("http");
const url = require("node:url");
const fs=require('fs')

const server = http.createServer((req, res) => {
  console.log(req.url,req.method);
  
  res.setHeader("Access-Control-Allow-Origin", "*");
  // res.writeHead(200, { "Content-Type": "application/json" });
  const path = url.parse(req.url).pathname;
  if(req.method=="OPTIONS"){
    // res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Methods","post")
    res.end(JSON.stringify({data:200}));
  }
  if(path=="/" &&  req.method == "GET"){
      let html=fs.readFileSync("./login.html")
      res.end(html)
  }

  //处理get请求
  //请求接口：localhost:3000/routes?page=1001
  if (path == "/routes" && req.method == "GET") {
    let page = Number(req.url.split("=")[1]);
    //判断page
    if (page == 1000) {
      res.end(
        JSON.stringify([
          {
            path: "/page1",
            component: "/page1.vue",
            name: "page1",
          },
          {
            path: "/page2",
            component: "/page2.vue",
            name: "page2",
          },
        ])
      );
    } else if (page == 1001) {
      res.end(
        JSON.stringify([
          {
            path: "/page1",
            component: "/page1.vue",
            name: "page1",
          },
          {
            path: "/page2",
            component: "/page2.vue",
            name: "page2",
          },
          {
            path: "/page3",
            component: "/page3.vue",
            name: "page3",
          },
          {
            path: "/page4",
            component: "/page4.vue",
            name: "page4",
          },
        ])
      );
    }
  }
  if (path == "/login" && req.method == "POST") {
    //还有判断请求数据，获取到请求体
    console.log("KKKK");
    let body = "";
    req.on("data", (chunk) => {
      body += chunk.toString();
    });
    req.on("end", () => {
      console.log(body);
      res.end(
        JSON.stringify({
          code: 200,
          msg: "登录成功",
        })
      );
    });
  }
});

server.listen(8080, () => {
  console.log("server is running");
});
